import pygame
from pygame.locals import *
from plane import *
import time


def start():
    # 1.创建一个窗口，用来显示内容
    screen = pygame.display.set_mode((480, 890), 0, 32)
    pygame.font.init()
    # 2.创建一个和窗口大小的图片，用来充当背景
    image_file_path = './feiji/background.png'
    background = pygame.image.load(image_file_path).convert()

    # 3. 创建一个玩家飞机对象
    player_plane = PlayerPlane(screen)

    # 4. 创建一个敌人飞机组
    enemy_group = EnemyGroup(screen)

    # 5. 创建一个得分板对象
    scoreboard = Scoreboard(screen)

    # 6.把背景图片放到窗口中显示
    while True:
        screen.blit(background, (0, 0))
        player_plane.display()
        enemy_group.display()
        enemy_group.move()
        enemy_group.launch_bullet()
        scoreboard.display()

        # 判断是否点击了退出按钮
        for event in pygame.event.get():
            if event.type == QUIT:
                print("Exit")
                exit()
            elif event.type == KEYDOWN:
                if event.key == K_a or event.key == K_LEFT:
                    player_plane.move_left()
                elif event.key == K_d or event.key == K_RIGHT:
                    player_plane.move_right()
                elif event.key == K_SPACE:
                    player_plane.launch_bullet()

        # 碰撞检测
        player_plane.check_collision(enemy_group, scoreboard)
        player_plane.check_collision(enemy_group, scoreboard)

        # 游戏结束判断
        if player_plane.is_hit:
            game_over(screen, scoreboard.score)

        pygame.display.update()


def game_over(screen, score):
    font = pygame.font.Font(None, 36)
    text = font.render("Game Over! Score: {}".format(score), True, (255, 0, 0))
    screen.blit(text, (150, 400))
    pygame.display.update()
    time.sleep(2)
    exit()


if __name__ == '__main__':
    start()
